package com.wzh.house.controller;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.wzh.common.utils.JwtUtil;
import com.wzh.house.entity.HouseAttrValueEntity;
import com.wzh.house.entity.RentHouseEntity;
import com.wzh.house.service.*;
import com.wzh.house.util.OssUtils;
import com.wzh.house.entity.NewImgEntity;
import com.wzh.house.vo.AttrValue;
import io.jsonwebtoken.Claims;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.wzh.house.entity.NewHouseEntity;
import com.wzh.common.utils.PageUtils;
import com.wzh.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 *
 * @author wzh
 * @email 1281204121@qq.com
 * @date 2022-03-22 19:04:17
 */
@RestController
@RequestMapping("house/newhouse")
public class NewHouseController {
    @Autowired
    private NewHouseService newHouseService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OssUtils ossUtils;
    @Autowired
    private NewImgService newImgService;

    @Autowired
    private HouseAttrValueService attrValueService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private NewUserAttentionService newUserAttentionService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 防刷 ---------------------
     */
    @RequestMapping("/fangshua/{houseId}/{userId}")
    public R fangshua(@PathVariable("houseId") Integer houseId,
                      @PathVariable("id")Long id, HttpServletRequest request){
        //生成一个随机数
        if (id==null){

            return R.error("客户端请求错误");
        }

        //限制访问次数 -------接口安全：接口防刷（接口限流）（防止接口恶意攻击导致服务宕机）
        String uri = request.getRequestURI();
        String key = uri + "_" + id;
        System.out.println(key);

        Integer count = (Integer) redisTemplate.opsForValue().get(key);
        System.out.println(count);

        if (count==null){//存入次数并且获取过期时间
            redisTemplate.opsForValue().set(key,1,30, TimeUnit.SECONDS);


        }else if (count<5){//可以访问
            //次数+1
            redisTemplate.opsForValue().set(key,count+1);

        }else {//超过5次

            return R.error("访问次数过多");
        }


        UUID uuid = UUID.randomUUID();
        System.out.println(uuid);
        redisTemplate.opsForValue().set(houseId+id,uuid,30, TimeUnit.SECONDS);

        return R.ok().setData(uuid);
    }




    //getbyId
    @RequestMapping("/getbyId/{houseId}")
    public R getbyId(@PathVariable("houseId") Integer houseId){
        NewHouseEntity newHouse = newHouseService.getById(houseId);
        return R.ok().put("newHouse", newHouse).setData(newHouse);
    }

    /**
     * 列表
     */
    @RequestMapping("/qianList")
    public R list(@RequestParam Map<String, Object> params,HttpServletRequest request){
        String token = request.getHeader("token");
        if (token==null){
            return R.error("用户未登录");
        }
        Claims claims = jwtUtil.parseJWT(token);
        if (claims==null||!"user".equals(claims.get("roles"))){
            return R.error("用户未登录");
        }
        params.put("userId",claims.getId());
        PageUtils page = newHouseService.selectByUserId(params);

        return R.ok().put("page", page);
    }
    /**
     * 前台列表
     */
    @RequestMapping("/list")
    public R qianList(@RequestParam Map<String, Object> params){
        PageUtils page = newHouseService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 审核查询列表
     * @param params
     * @return
     */
    @RequestMapping("checkList")
    public R checkList(@RequestParam Map<String, Object> params){
        PageUtils page = newHouseService.checkList(params);

        return R.ok().put("page", page);
    }
    /**
     * 新房、二手房审核
     */
    @RequestMapping("/updateStatus")
    public R updateStatus(@RequestParam Integer houseId ,@RequestParam Integer status){
        Integer i = newHouseService.updateStatus(houseId,status);
        if (i>0){
            //mq发短信
            HashMap<String, Object> map = new HashMap<>();
            map.put("houseId",houseId);
            map.put("status",status);
            rabbitTemplate.convertAndSend("msg",map);
            return R.ok();
        }
        return R.error();
    }

    @RequestMapping("getById")
    public R getById(@RequestParam("id")Integer id){
        NewHouseEntity byId = newHouseService.getById(id);
        return R.ok().setData(byId);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{houseId}")
    public R info(@PathVariable("houseId") Integer houseId,HttpServletRequest request){
		NewHouseEntity newHouse = newHouseService.getById(houseId);
        HouseAttrValueEntity attrValueEntity=attrValueService.getOneByHouseId(houseId);
        List<AttrValue> attrs = JSON.parseObject(attrValueEntity.getAttrValue(), new TypeReference<List<AttrValue>>() {
        });
        newHouse.setAttrKeys(attrs);
        String token = request.getHeader("token");
        if (token!=null) {
            Claims claims = jwtUtil.parseJWT(token);
            if (claims!=null&&"user".equals(claims.get("roles"))) {
                Integer i = newUserAttentionService.getCountByNewAndUserId(houseId,Integer.valueOf(claims.getId()));
                if (i>0){
                    newHouse.setAttention(true);
                }
            }
        }
        return R.ok().put("newHouse", newHouse);
    }

    /**
     * 前台发布
     */
    @RequestMapping("/qianSave")
    @Transactional
    public R qianSave(@RequestBody NewHouseEntity newHouse, HttpServletRequest request){
        String token = request.getHeader("token");
        if (token==null){
            return R.error("用户未登录");
        }
        Claims claims = jwtUtil.parseJWT(token);
        if (claims==null||!"user".equals(claims.get("roles"))){
            return R.error("用户未登录");
        }
        newHouse.setUserId(Integer.valueOf(claims.getId()));
        //,1.jpeg,2.jpeg
        String[] split = newHouse.getDefaultImg().substring(1).split(",");
        newHouse.setDefaultImg(split[0]);//默认图片为第一张
        newHouse.setStatus(3);//审核中
        boolean save = newHouseService.save(newHouse);
        if (save){
            //添加属性
            HouseAttrValueEntity houseAttrValueEntity = new HouseAttrValueEntity();
            houseAttrValueEntity.setHouseId(newHouse.getHouseId());
            houseAttrValueEntity.setCreateTime(new Date());
            houseAttrValueEntity.setAttrValue(JSON.toJSONString(newHouse.getAttrKeys()));
            attrValueService.save(houseAttrValueEntity);
            //添加图片到图片表里 批量添加
            ArrayList<NewImgEntity> newImgEntities = new ArrayList<>();
            for (String s : split) {
                NewImgEntity newImgEntity = new NewImgEntity();
                newImgEntity.setHouseId(newHouse.getHouseId());
                newImgEntity.setImgUrl(s);
                if (s.equals(split[0])){
                    newImgEntity.setImgDefault(0);//是否为默认(0.是1.否)
                }else {
                    newImgEntity.setImgDefault(1);
                }
                newImgEntities.add(newImgEntity);
            }
            newImgService.saveBatch(newImgEntities);
        }
        return R.ok();
    }

    /**
     * 后台发布
     * @param newHouse
     * @param
     * @return
     */
    @RequestMapping("/save")
    @Transactional
    public R save(@RequestBody NewHouseEntity newHouse){
        //,1.jpeg,2.jpeg
        String[] split = newHouse.getDefaultImg().substring(1).split(",");
        newHouse.setDefaultImg(split[0]);//默认图片为第一张
        boolean save = newHouseService.save(newHouse);
        if (save){
            //添加属性
            HouseAttrValueEntity houseAttrValueEntity = new HouseAttrValueEntity();
            houseAttrValueEntity.setHouseId(newHouse.getHouseId());
            houseAttrValueEntity.setCreateTime(new Date());
            houseAttrValueEntity.setAttrValue(JSON.toJSONString(newHouse.getAttrKeys()));
            attrValueService.save(houseAttrValueEntity);
            //添加图片到图片表里 批量添加
            ArrayList<NewImgEntity> newImgEntities = new ArrayList<>();
            for (String s : split) {
                NewImgEntity newImgEntity = new NewImgEntity();
                newImgEntity.setHouseId(newHouse.getHouseId());
                newImgEntity.setImgUrl(s);
                if (s.equals(split[0])){
                    newImgEntity.setImgDefault(0);//是否为默认(0.是1.否)
                }else {
                    newImgEntity.setImgDefault(1);
                }
                newImgEntities.add(newImgEntity);
            }
            newImgService.saveBatch(newImgEntities);
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @Transactional
    public R update(@RequestBody NewHouseEntity newHouse){
        //删除图片表里之前的图片 批删
        newImgService.removeByHouseId(newHouse.getHouseId());
        String[] split = newHouse.getDefaultImg().substring(1).split(",");
        newHouse.setDefaultImg(split[0]);//默认图片为第一张
        boolean b = newHouseService.updateById(newHouse);//修改
        if (b){
            //添加图片到图片表里 批量添加
            ArrayList<NewImgEntity> newImgEntities = new ArrayList<>();
            for (String s : split) {
                NewImgEntity newImgEntity = new NewImgEntity();
                newImgEntity.setHouseId(newHouse.getHouseId());
                newImgEntity.setImgUrl(s);
                if (s.equals(split[0])){
                    newImgEntity.setImgDefault(0);//是否为默认(0.是1.否)
                }else {
                    newImgEntity.setImgDefault(1);
                }
                newImgEntities.add(newImgEntity);
            }
            newImgService.saveBatch(newImgEntities);
        }

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @Transactional
    public R delete(@RequestBody Integer[] houseIds){
        boolean b = newHouseService.removeByIds(Arrays.asList(houseIds));
        if (b){
            //删除属性，图片
            for (Integer houseId : houseIds) {
                newImgService.removeByHouseId(houseId);
            }
            attrValueService.removeByHouseIds(houseIds);
        }
        return R.ok();
    }

    /**
     * 查询所有房屋
     */
    @RequestMapping("esNewList")
    public R esNewList(){
        return newHouseService.esNewList();
    }

    /**
     * 图片上传
     */
    @RequestMapping("/upload")
    public R upload(MultipartFile file){
        R r = ossUtils.uploadFile(file);
        return r;
    }

    /**
     * 爬取信息加入数据库中 慎用！
     */
    @RequestMapping("/papa")
    public R papa(){
        newHouseService.papaSave();
      return R.ok();
    }

    @Autowired
    private RentHouseService rentHouseService;

    @Autowired
    private RestHighLevelClient client;

    @Scheduled(cron = "0 30 * * * *")
    public void scheduled(){

//        List<NewHouseEntity> list = newHouseService.list();
//        for (NewHouseEntity newHouseEntity : list) {
//            IndexRequest request = new IndexRequest("buyhour");
//            request.id(newHouseEntity.getHouseId()+"");
//            String jsonString = JSONObject.toJSONString(newHouseEntity);
//            request.source(jsonString, XContentType.JSON);
//            try {
//                IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        List<RentHouseEntity> list1 = rentHouseService.list();
        for (RentHouseEntity rentHouseEntity : list1) {
            IndexRequest request = new IndexRequest("renhour");
            request.id(rentHouseEntity.getHouseId()+"");
            String jsonString = JSONObject.toJSONString(rentHouseEntity);
            request.source(jsonString, XContentType.JSON);
            try {
                IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
